﻿using UnityEngine;

namespace Core
{
    /// <summary>
    /// 弹窗
    /// </summary>
    public abstract class UIPopView : UIWidget, IUpdate
    {
        public bool IsPopView { get; set; } = true;

        public virtual void Update()
        {
            if (Active == false || IsPopView == false)
            {
                return;
            }

            if (Input.GetMouseButtonDown(0))
            {
                var results = Utils.Touch.RaycastGui(Input.mousePosition);
                for (int i = 0; i < results.Count; i++)
                {
                    var result = results[i];
                    if (Utils.Trans.IsDirectRelative(result.gameObject.transform, transform))
                    {
                        return;
                    }
                }
                SetActive(false);
            }
        }

        public void Locate(AbstractWindow wnd, GameObject obj)
        {
            if (IsPopView == false) return;

            var rect = obj.GetComponent<RectTransform>();
            var rect1 = gameObject.GetComponent<RectTransform>();

            Vector3 offset1;
            float offset2;

            if (CheckDown(wnd, obj))
            {
                offset1 = new Vector3(rect.sizeDelta.x * 0.5f, -rect.sizeDelta.y, 0);
                offset2 = -rect1.sizeDelta.y * 0.5f;
            }
            else
            {
                offset1 = new Vector3(rect.sizeDelta.x * 0.5f, 0, 0);
                offset2 = rect1.sizeDelta.y * 0.5f;
            }

            var localPos = obj.transform.localPosition + offset1;
            var pos = obj.transform.parent.TransformPoint(localPos);
            var cam = wnd.canvas.worldCamera;
            var screenPoint = cam.WorldToScreenPoint(pos);
            RectTransformUtility.ScreenPointToLocalPointInRectangle(wnd.rootRect, screenPoint, cam, out var tgtLocalPos);
            tgtLocalPos.y += offset2;
            transform.localPosition = tgtLocalPos;
        }

        private bool CheckDown(AbstractWindow wnd, GameObject obj)
        {
            var rect = obj.GetComponent<RectTransform>();
            var localPos = obj.transform.localPosition + new Vector3(rect.sizeDelta.x * 0.5f, -rect.sizeDelta.y, 0);

            var rect1 = transform.GetComponent<RectTransform>();
            var anchor_pos = localPos + new Vector3(0, -rect1.sizeDelta.y, 0);
            var pos = obj.transform.parent.TransformPoint(anchor_pos);
            var cam = wnd.canvas.worldCamera;
            var screenPoint = cam.WorldToScreenPoint(pos);
            if (screenPoint.y < 0)
            {
                return false;
            }
            return true;
        }
    }
}
